<template>
  <div>
    <q-input
      dense
      outlined
      v-model.lazy="myData"
    >
      <template v-slot:after>
        <q-btn
          dense
          unelevated
          color="primary"
          label="选择"
          @click="onClick"
        />
      </template>
    </q-input>

    <q-dialog class="my-dialog" v-model="isFlagShow" @mousedown.stop>
      <q-card class="my-card q-mx-lg">
        <q-toolbar class="row items-center my-form-header">
          <div>
            {{message}}
          </div>
          <q-space />
          <q-btn
            flat
            round
            dense
            icon="mdi-close"
            @click="onClose"
          />
        </q-toolbar>
        <q-separator />
        <q-card-setion class="q-mx-sm">
          <div class="col q-gutter-xs">
            <q-item class="items-center">
              <q-item-label>项目：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="projectArr"
                  v-model="project"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @update:model-value="onProjectUpdate(project)"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label>设备：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="deviceOptions"
                  v-model="device"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @update:model-value="onDeviceUpdate(device)"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label>变量：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="variableOptions"
                  v-model.lazy="variable"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @update:model-value="onVariableUpdate"
                />
              </q-item-section>
            </q-item>
          </div>
        </q-card-setion>
        <q-separator />
        <div class="q-gutter-sm my-form-footer">
          <q-btn
            unelevated
            dense
            label="确定"
            type="submit"
            color="teal-3"
            @click="onSubmit"
            style="width: 80px"
          />
        </div>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, computed, onMounted, PropType } from  'vue';
import api from 'axios'
import { uivCatalogUrlAPI, uivBaseVOAPI } from 'src/util/UivBaseConst';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import { cataItem } from 'src/hook/common/useCatalogType';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';

interface VarItemVO {
  id: number,
  variableName: string,
  projectId: number,
  projectName: string,
  deviceName: string,
}

export default defineComponent({
  name: 'VariableSelectBox',
  props: {
    message: {
      type: String,
      default: () => {
        return '变量选择'
      }
    },

    name: {
      type: String,
      default: () => {
        return ''
      }
    },

    data: {
      type: Number,
      default: () => {
        return 0
      }
    },

    projectArr: {
      type: Array as PropType<cataItem[]>,
      default: () => {
        return [];
      }
    }
  },

  emits: ['update:name', 'update:data'],
  setup (props, context) {
    //解构
    const {
      message,
      name,
      data,
      projectArr
    } = toRefs(props)

    //消息通知
    const {
      showMessage
    } = useMessageNotify();

    const {
      findCatalogId
    } = useCatalogTool()

    //当前变量信息
    let param = ref<VarItemVO>({
      id: 0,
      variableName: '',
      projectId: 0,
      projectName: '',
      deviceName: ''
    });

    //定义响应数据
    let myData = computed({
      get: () => {
        return data.value;
      },
      set: (dv: number) => {
        context.emit('update:data', dv);
      }
    });

    let myName = computed({
      get: () => {
        return name.value;
      },

      set: (cn: string) => {
        context.emit('update:name', cn);
      }
    });

    //选择按钮
    const onClick = () => {
      isFlagShow.value = true;
    }

    //对话框显示
    let isFlagShow = ref(false);
    let project = ref('请选择项目');
    let device = ref('请选择设备');
    let variable = ref('请选择变量');
    let deviceOptions = ref< cataItem[]>([]);
    let variableOptions = ref< cataItem[]>([]);


    //根据变量ID，读取项目名称，设备名称和变量名称
    const getAll = () => {
      //读取变量信息
      if (data.value > 0) {
        api.post(uivBaseVOAPI.UIV_VAR_VO_LIST_API, {
          id: data.value
        }).then((res) => {
          if (res.data.message === 'Success') {
            let item: VarItemVO = res.data.data;

            //console.log(res.sheet.sheet);
            param.value.id = data.value;
            param.value.variableName = item.variableName;
            param.value.projectId = item.projectId;
            param.value.projectName = item.projectName;
            param.value.deviceName = item.deviceName;
          } else {
            showMessage(res.data.message);
          }
        }).catch((error) => {
          showMessage(error.message);
        });
      }
    }

    //读取设备信息
    const getDevice = (pid: number) => {
      if (pid > 0) {
        api.post(uivCatalogUrlAPI.DEVICE_LIST_API, {
          id: pid
        }).then((res) => {
          if (res.data.message === 'Success') {
            deviceOptions.value.length = 0;
            let list: cataItem[] = res.data.data;
            list.forEach((item) => {
              deviceOptions.value.push(item);
            });

            //更新variable列表
            let pid = findCatalogId(deviceOptions.value, device.value);
            getVariable(pid);
          }
        })
      }
    }

    //读取变量信息
    const getVariable = (did: number) => {
      if (did > 0) {
        api.post(uivCatalogUrlAPI.VARIABLE_LIST_API, {
          id: did
        }).then((res) => {
          if (res.data.message === 'Success') {
            variableOptions.value.length = 0;
            let list: cataItem[] = res.data.data;
            list.forEach((item) => {
              variableOptions.value.push(item);
            });
          }
        })
      }
    }

    //项目变化，对应设备列表发生变化
    const onProjectUpdate = (name: string) => {
      let pid = findCatalogId(projectArr.value, name);

      //项目变化，更新设备列表
      if (pid > 0) {
        //console.log(pid);
        getDevice(pid);
      }
    }

    //设备变化，对应变量列表发生变化
    const onDeviceUpdate = (v: string) => {
      let did = findCatalogId(deviceOptions.value, v);

      //设变变化，更新变量列表
      getVariable(did);
    }

    //变量变化，更新input
    const onVariableUpdate = () => {
      let vid = findCatalogId(variableOptions.value, variable.value);
      if (vid > 0) {
        myData.value = vid;
        myName.value = variable.value;
      }
    }

    //关闭窗口
    const onClose = () => {
      isFlagShow.value = false;
    }

    //提交窗口
    const onSubmit = () => {
      isFlagShow.value = false;
    }

    //初始化
    const init = () => {
      //根据变量id读取相关信息
      getAll();

      //根据项目读取设备
      if (param.value.projectId > 0) {
        getDevice(param.value.projectId);
      }
    }

    //组件挂载
    onMounted(() => {
      init();
    })

    return {
      message,
      myData,
      myName,
      onClick,

      isFlagShow,
      project,
      device,
      variable,
      projectArr,
      deviceOptions,
      variableOptions,
      onProjectUpdate,
      onDeviceUpdate,
      onVariableUpdate,
      onClose,
      onSubmit,
      init
    };
  }
});

</script>

<style lang="scss" scoped>
  .my-dialog {
    .my-card {
      width: 300px;
      max-width: 600px;

      .my-form-header {
        background-color: #e3dede;
        font-size: 18px;
      }
      .my-form-container {
        text-align: center;
        padding: 5px;
        height: 180px;
      }
      .my-form-footer {
        text-align: right;
        padding: 5px;
        background-color: #cecaca;
      }
    }
  }
</style>
